package com.ruoyi.project.mobile.order;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.RFactory;
import com.ruoyi.common.utils.mobile.weixin.template.AddOrderMsg;
import com.ruoyi.common.utils.uniquekey.IdGererateFactory;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.AppBeanInjector;
import com.ruoyi.project.system.address.domain.MemberAddress;
import com.ruoyi.project.system.address.service.IMemberAddressService;
import com.ruoyi.project.system.coinrecord.domain.HondaCoinRecord;
import com.ruoyi.project.system.coinrecord.service.IHondaCoinRecordService;
import com.ruoyi.project.system.goods.cart.service.IShoppingCartService;
import com.ruoyi.project.system.goods.goods.domain.GoodsDto;
import com.ruoyi.project.system.goods.goods.domain.GoodsGoods;
import com.ruoyi.project.system.goods.goods.service.IGoodsGoodsService;
import com.ruoyi.project.system.goods.product.domain.GoodsProduct;
import com.ruoyi.project.system.goods.product.service.IGoodsProductService;
import com.ruoyi.project.system.hondaconfig.service.IHondaConfigService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.order.comment.service.IOrderCommentService;
import com.ruoyi.project.system.order.commentimg.service.ICommentImgService;
import com.ruoyi.project.system.order.order.domain.OrderOrder;
import com.ruoyi.project.system.order.order.dto.OrderOrderDto;
import com.ruoyi.project.system.order.order.enums.OrderStatus;
import com.ruoyi.project.system.order.order.service.IOrderOrderService;
import com.ruoyi.project.system.order.ordergoods.domain.OrderGoods;
import com.ruoyi.project.system.order.ordergoods.dto.OrderGoodsDto;
import com.ruoyi.project.system.order.ordergoods.service.IOrderGoodsService;
import com.ruoyi.project.system.paylog.service.IPayLogService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能：
 *
 * @author：dell
 * @create：2020/6/22 18:54
 * @version：2020 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
@RestController
@RequestMapping("/api/order")
public class ApiOrderController extends BaseController {

	@Autowired
	private IMemberAddressService memberAddressService;

	@Autowired
	private IGoodsGoodsService goodsGoodsService;

	@Autowired
	private IMemberService memberService;

	@Resource
	private IdGererateFactory idGererateFactory;

	@Autowired
	private IOrderOrderService orderOrderService;

	@Autowired
	private IOrderGoodsService orderGoodsService;

	@Autowired
	private IGoodsProductService goodsProductService;

	@Autowired
	private IOrderCommentService orderCommentService;
	
	@Autowired
	private ServerConfig serverConfig;

	@Autowired
	private ICommentImgService commentImgService;

	@Autowired
	private IShoppingCartService shoppingCartService;

	@Autowired
	private IPayLogService payLogService;

	@Autowired
	private IHondaConfigService hondaConfigService;

	@Autowired
	private IHondaCoinRecordService hondaCoinRecordService;

	@GetMapping("/ready")
	public R readyOrder(@RequestParam String uid,@RequestParam String productIds,@RequestParam Integer nums){
		HashMap<String, Object> map = new HashMap<>();
		//查询默认地址信息
		MemberAddress memberAddress = this.memberAddressService.findDefault(uid);
		map.put("address",memberAddress);
		//查询商品信息
		BigDecimal sumGoodsPrice = new BigDecimal(0);
		BigDecimal sumPostFee = new BigDecimal(0);
		int goodsCount = 0;
		ArrayList<GoodsDto> goodsDtos = new ArrayList<>();
			GoodsDto goodsDto = this.goodsGoodsService.findGoodsDtoByPId(productIds);
			goodsDto.setTotal(nums);
			goodsDto.setSpecId(productIds);
			goodsDtos.add(goodsDto);
			sumGoodsPrice=sumGoodsPrice.add(goodsDto.getPriceN().multiply(new BigDecimal(nums)));
			sumPostFee=sumPostFee.add(goodsDto.getPostFee());
			goodsCount=goodsCount+nums;
		map.put("sumPostFee",sumPostFee);
		map.put("sumGoodsPrice",sumGoodsPrice);
		map.put("sumPrice",sumGoodsPrice.add(sumPostFee));
		map.put("goods",goodsDtos);
		map.put("goodsCount",goodsCount);
		return RFactory.generateR(map);
	}

	/**
	 * 新增订单
	 * @param orderOrderDto
	 * @return
	 */
	@PostMapping
	@Transactional
	public R addOrder(@RequestBody OrderOrderDto orderOrderDto){
		//判断用户积分是否充足
		Member member = this.memberService.selectMemberById(orderOrderDto.getUserId());
		if(member.getCoin().compareTo(orderOrderDto.getPriceRealPay())==-1){
			return R.error("积分不足");
		}

		//判断商品库存是否充足
		for(OrderGoodsDto orderGoods:orderOrderDto.getGoodsList()){
			GoodsProduct goodsProduct = this.goodsProductService.selectGoodsProductById(orderGoods.getProductId());
			if(goodsProduct.getStock()<orderGoods.getTotal()){
				return R.error("库存不足,请重新下单");
			}
			//修改商品库存
			GoodsGoods oldGoods = this.goodsGoodsService.selectGoodsGoodsById(goodsProduct.getGoodsId());
			orderOrderDto.getGoodsList().get(0).setGoodsName(oldGoods.getName());
			//判断商品是否下架
			if(oldGoods.getStatus()!=0){
				return R.error("商品 "+oldGoods.getName()+" 已下架");
			}
			//判断该规格是否被删除
			if(goodsProduct.getStatus()==1){
				return R.error("商品 "+oldGoods.getName()+" 规格发生变化,请重新选择");
			}
			//修改库存
			goodsProduct.setStock(goodsProduct.getStock()-orderGoods.getTotal().intValue());
			this.goodsProductService.updateGoodsProduct(goodsProduct);
			GoodsGoods updateGoods = new GoodsGoods();
			updateGoods.setId(oldGoods.getId());
			updateGoods.setStock(oldGoods.getStock()-orderGoods.getTotal());
			//增加销量
			updateGoods.setMonthlySales(oldGoods.getMonthlySales()+orderGoods.getTotal());
			this.goodsGoodsService.updateGoodsGoods(updateGoods);
		}

		//生成 上级订单ID
		String superOrderId = "";
		if(orderOrderDto.getGoodsList().size()>1){
			superOrderId = this.idGererateFactory.nextId().toString();
		}

		String orderId = "";

		for(OrderGoods orderGoods:orderOrderDto.getGoodsList()){
			GoodsProduct goodsProduct = this.goodsProductService.selectGoodsProductById(orderGoods.getProductId());
			orderGoods.setGoodsId(goodsProduct.getGoodsId());
			orderGoods.setPriceN(goodsProduct.getPriceN());
			orderGoods.setPriceO(goodsProduct.getPriceO());
			OrderOrder order = new OrderOrder();
			order.setPayType(orderOrderDto.getPayType());
			order.setUserId(orderOrderDto.getUserId());
			order.setPostFee(orderGoods.getPostFee());
			order.setPricePay(goodsProduct.getPriceN().multiply(new BigDecimal(orderGoods.getTotal())).add(order.getPostFee()));
			order.setPriceRealPay(order.getPricePay());
			order.setBuyerMsg(orderOrderDto.getBuyerMsg());
			order.setConsigneeName(orderOrderDto.getConsigneeName());
			order.setConsigneeTel(orderOrderDto.getConsigneeTel());
			order.setAddress(orderOrderDto.getAddress());
			order.setArea(orderOrderDto.getArea());
			if(orderOrderDto.getGoodsList().size()>1){
				order.setSuperOrderId(superOrderId);
			}

			order.setOrderNo(this.idGererateFactory.nextId().toString());
			orderOrderDto.setOrderNo(order.getOrderNo());
			if(orderOrderDto.getPayType()==0){
				order.setStatus(OrderStatus.TO_BE_PAID.getValue());
			}else{
				order.setStatus(OrderStatus.TO_BE_DELIVERED.getValue());
			}
			order.setCreated(DateUtils.getNowDate());
			order.setDelFlag(0);
			this.orderOrderService.insertOrderOrder(order);
			//添加订单下的产品信息
			orderGoods.setOrderId(order.getId());
			orderGoods.setHasComent(0);
			this.orderGoodsService.insertOrderGoods(orderGoods);

			if(orderOrderDto.getGoodsList().size()>1){
				order.setSuperOrderId(superOrderId);
				orderId = superOrderId;
			}else{
				orderId = order.getId();
			}
		}

		//扣除用户积分
		Member updateMember = new Member();
		updateMember.setId(member.getId());
		updateMember.setCoin(member.getCoin().subtract(orderOrderDto.getPriceRealPay()));
		this.memberService.updateMember(updateMember);
		//生成支付记录
		HondaCoinRecord hondaCoinRecord = new HondaCoinRecord();
		hondaCoinRecord.setMemberId(member.getId());
		hondaCoinRecord.setType(1);
		hondaCoinRecord.setStatus(1);
		hondaCoinRecord.setResId(orderId);
		hondaCoinRecord.setCreated(DateUtils.getNowDate());
		hondaCoinRecord.setNum(orderOrderDto.getPriceRealPay());
		hondaCoinRecord.setGetType(0);
		this.hondaCoinRecordService.insertHondaCoinRecord(hondaCoinRecord);


		//发送订单推送消息
        List<String> orderMemberList = AppBeanInjector.weixinConfig.getOrderMemberList();
        //通知相关人员
        for(int i=0;i<orderMemberList.size();i++){
            AddOrderMsg addOrderMsg = new AddOrderMsg();
            addOrderMsg.setToOpenId(orderMemberList.get(i));
            HashMap<String, String> data = new HashMap<>();
            data.put("created",DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
            data.put("goodsName",orderOrderDto.getGoodsList().get(0).getGoodsName());
            data.put("orderNo",orderOrderDto.getOrderNo());
            addOrderMsg.setContentMsg(data);
            AppBeanInjector.weixinTemplateMsgService.pushMsg(addOrderMsg);//
        }
		return RFactory.generateR(orderId);

	}

	/**
	 * 查询订单列表
	 * @param status
	 * @param uid
	 * @return
	 */
	@GetMapping
	public R orderList(@RequestParam(required = false) Integer[] status,@RequestParam String uid){
		startPage();
		List<OrderOrderDto> orderOrderDtos = this.orderOrderService.findListByStatusAndUid(status,uid);
		if(orderOrderDtos!=null){
			for(OrderOrderDto orderDto:orderOrderDtos){
				orderDto.setStatusName(OrderStatus.getByValue(orderDto.getStatus()).getName());
				orderDto.setGoodsList(this.orderGoodsService.findListByOrderId(orderDto.getId()));
			}
		}
		return RFactory.generateR(getDataTable(orderOrderDtos));
	}


	/**
	 * 查询订单详情
	 * @param id
	 * @return
	 */
	@GetMapping("/info")
	public R orderInfo(@RequestParam String id){
		OrderOrderDto orderDto = this.orderOrderService.findByOrderId(id);
		if(orderDto!=null){
			orderDto.setStatusName(OrderStatus.getByValue(orderDto.getStatus()).getName());
			orderDto.setGoodsList(this.orderGoodsService.findListByOrderId(id));
			return RFactory.generateR(orderDto);
		}else{
			List<OrderOrderDto> listBySuperOId = this.orderOrderService.findListBySuperOId(id);
			if(listBySuperOId==null||listBySuperOId.size()==0){
				return R.error("订单不存在");
			}
			OrderOrderDto order = listBySuperOId.get(0);
			ArrayList<OrderGoodsDto> orderGoods = new ArrayList<>();

			BigDecimal price = new BigDecimal(0);
			for(OrderOrderDto orderOrderDto:listBySuperOId){
				OrderGoodsDto orderGoodsDto = this.orderGoodsService.findListByOrderId(orderOrderDto.getId()).get(0);
				price = price.add(orderGoodsDto.getPriceN().multiply(new BigDecimal(orderGoodsDto.getTotal())).add(orderOrderDto.getPostFee())).setScale(2,BigDecimal.ROUND_HALF_UP);
				orderGoods.add(orderGoodsDto);
			}
			order.setGoodsList(orderGoods);
			order.setPriceRealPay(price.setScale(2,BigDecimal.ROUND_HALF_UP));
			order.setOrderNo(id);
			order.setStatusName(OrderStatus.getByValue(order.getStatus()).getName());
			return RFactory.generateR(order);

		}

	}

    /**
     * 订单收货
     * @param map
     * @return
     */
    @PostMapping("/receipt")
    public R orderReceipt(@RequestBody Map map){
        String uid = (String) map.get("uid");
        String id = (String) map.get("id");

        //判断订单信息是否存在
        OrderOrder orderOrder = this.orderOrderService.selectOrderOrderById(id);
        //订单不存在 或者 订单并非当前用户 或者 订单 状态不是待收货
        if(orderOrder==null||!orderOrder.getUserId().equals(uid)||!orderOrder.getStatus().equals(OrderStatus.TO_BE_RECEIVED.getValue())){
            return R.error("订单未找到");
        }
        OrderOrder update = new OrderOrder();
        update.setStatus(OrderStatus.COMPLETE.getValue());
        update.setId(id);
        update.setCloseTime(DateUtils.getNowDate());
        this.orderOrderService.updateOrderOrder(update);

        return R.ok();
    }

    /**
     * 查询快递信息
     * @param uid
     * @param id
     * @return
     */
    @GetMapping("/express")
    public R orderExpress(@RequestParam String uid,@RequestParam String id){
        //查询订单是否存在
        OrderOrderDto byOrderId = this.orderOrderService.findByOrderId(id);
        if(byOrderId==null||!byOrderId.getUserId().equals(uid)){
            return R.error("订单不存在");
        }
        byOrderId.setGoodsList(this.orderGoodsService.findListByOrderId(id));
        try {
//            JSONObject yd = AppBeanInjector.expressUtil.getOrderTracesByJson(byOrderId.getShippingCompanyCode(), byOrderId.getShippingMobile());
			JSONObject expressJsonData = AppBeanInjector.kd100Util.getExpressJsonData(byOrderId.getShippingCompanyCode(), byOrderId.getShippingMobile());
            HashMap<String, Object> map = new HashMap<>();
            map.put("order",byOrderId);
            map.put("express",expressJsonData.toString());
            return RFactory.generateR(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

}
